package com.zywl.web.filter;

import com.zywl.core.beans.Member;
import com.zywl.service.MemberService;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.BrokenBarrierException;

public class LoginFilter implements Filter {
    private FilterConfig config;



    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession();
        String noFilterPaths = config.getInitParameter("noFilterPaths");

        String uri = request.getRequestURI();

        if (uri != null && uri.endsWith("/")) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

//        if (uri != null && uri.endsWith("/api")) {
//            String token = request.getHeader("token");
//            String melTel = request.getHeader("mebTel");
//            String token1 = TokenUtils.verifyToken(token);//验证成功获取用户手机号
//            Member member = memberService.selectMemberByMebTel(melTel);
//            if(melTel!=token1 || member==null){
//                return ;
//            }
//        }


        if (noFilterPaths != null) {
            String[] path = noFilterPaths.split(";");
            for (int i = 0; i < path.length; i++) {

                if (StringUtils.isNotEmpty(path[i]) && uri.contains(path[i])) {
                    chain.doFilter(request, response);
                    return;
                }
            }

        }
        if (session.getAttribute(Constants.USER_SESSION_KEY) != null) {
            chain.doFilter(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/deny");
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

}
